package apiTestBusiness;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import easyDAO.SqlDispatch;
import impl.TestServerBusinessImpl;
import models.MyConfig;
import models.SqlReturnModel;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

/**
 * Created by yangxianming on 2015-09-29.
 */
public class GetApiList implements TestServerBusinessImpl {

    @Override
    public String doIt(HttpServletRequest request, MyConfig myConfig) {
        JSONObject returnJson = JSON.parseObject("{\"apistatus\":0,\"result\":\"\",\"errorMsg\":\"\"}");
        //获取所属项目 三个参数key必须要填value可以是空
        String project = request.getParameter("project");
        String method = request.getParameter("method");
        String path = request.getParameter("path"); //这个支持模糊查找
        String version = request.getParameter("version"); //这个支持模糊查找

        //执行sql操作
        SqlDispatch sqlDispatch = new SqlDispatch(myConfig);
        //
        String sqlWhereString = "";
        ArrayList<String> sqlWhereArr = new ArrayList<String>();
        if (project != null && !project.isEmpty())
            sqlWhereArr.add("project=\"" + project + "\"");
        if (method != null && !method.isEmpty())
            sqlWhereArr.add("method=\"" + method + "\"");
        if (path != null && !path.isEmpty())
            sqlWhereArr.add("path LIKE \"%" + path + "%\"");
        if (version != null && !version.isEmpty())
            sqlWhereArr.add("version=\"" + version + "\"");
        if (sqlWhereArr.size() > 0)
            sqlWhereString = "where " + String.join(" AND ", sqlWhereArr);
        //这个select查询被测接口
        //SELECT * from beingtestedapi where method="get" AND project="1" AND path LIKE "%3";
        String sqlWord = "SELECT * FROM testedapi " + sqlWhereString + " ORDER BY id DESC";
        //
        SqlReturnModel sqlReturnModel = sqlDispatch.select("*", "testedapi", sqlWhereString, "id");

        //将组装返回参数
        String apistatus = (sqlReturnModel.getIsSuccess()) ? "1" : "0";
        returnJson.put("apistatus", apistatus);
        returnJson.put("errorMsg", sqlReturnModel.getFailingReason());

        //将select的数据塞进返回参数
        JSONObject apiData = new JSONObject();
        JSONArray apiList = new JSONArray();
        ArrayList<ArrayList<String>> resultArr = sqlReturnModel.getSelectReturnData();
        for (ArrayList<String> line: resultArr){
            JSONObject oneApi = new JSONObject();
            JSONArray jsonLine = new JSONArray();
            for (String a: line){
                jsonLine.add(a);
            }
            oneApi.put("data", jsonLine);
            apiList.add(oneApi);
        }
        apiData.put("datas", apiList);
        returnJson.put("result", apiData);

        return returnJson.toString();
    }

}